package com.ilvyou.api.service;

import com.ilvyou.api.util.RemoteUtil;
import com.ilvyou.core.base.BaseService;
import com.ilvyou.core.dao.Criteria;
import com.ilvyou.core.dao.Dao;
import com.ilvyou.core.util.StringUtil;
import com.ilvyou.core.util.Util;
import com.ilvyou.data.lhf.*;
import com.ilvyou.data.lvzan.AppUserEntity;
import com.ilvyou.data.lvzan.BppCompanyApplyEntity;
import com.ilvyou.data.lvzan.BppCompanyEntity;
import com.ilvyou.data.lvzan.BppUserEntity;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Map;

/**
 * Created by GuanYuCai on 16/9/16.
 */
@Service
public class PersonalService extends BaseService {

    @Resource(name = "lhfDao")
    private Dao lhfDao;

    @Resource(name = "zanDao")
    private Dao zanDao;

    @Override
    protected Dao getDao() {
        return lhfDao;
    }

    public void addAnswer(Long actId, String question, String answer) throws Exception {
        ScrAnswerEntity a = lhfDao.get(ScrAnswerEntity.class, new Criteria().add("actid=?", actId));
        if(a == null){
            ScrAlipayEntity alipay = lhfDao.get(ScrAlipayEntity.class, new Criteria().add("actid=?", actId));
            a = new ScrAnswerEntity();
            a.setId(Util.createId());
            a.setActid(actId);
            a.setActname(alipay.getActname());
            a.setQuestion(question);
            a.setAnswer(answer);
            a.setCreatedname(alipay.getActname());
            a.setCreatedby(actId);
            a.setLastedname(alipay.getActname());
            a.setLastedby(actId);
            lhfDao.insert(a);
        }else{
            a.setQuestion(question);
            a.setAnswer(answer);
            a.setLastedon(new Timestamp(System.currentTimeMillis()));
            lhfDao.update(a);
        }
    }

    public void updatePayPassword(Long actId, String payPassword) throws Exception{
        ScrAnswerEntity answer = lhfDao.get(ScrAnswerEntity.class, new Criteria().add("actid=?", actId));
        AlipayAccountEntity account = lhfDao.getByPK(AlipayAccountEntity.class, actId);
        ScrAlipayEntity alipay = lhfDao.getByPK(ScrAlipayEntity.class, actId);
        payPassword = StringUtil.base64Decode(payPassword);
        payPassword = RemoteUtil.getMd5Pwd(payPassword, alipay.getSalt());

        account.setPaypassword(payPassword);
        account.setEnableflag((short) (answer == null ? 0 : 1));
        account.setLastedon(new Timestamp(System.currentTimeMillis()));
        lhfDao.update(account);

        alipay.setEnableflag((short) (answer == null ? 0 : 1));
        alipay.setLastedon(new Timestamp(System.currentTimeMillis()));
        lhfDao.update(alipay);
    }

    public void updateMobile(Long actId, String mobile) throws Exception{
        ScrAlipayEntity alipay = getByPK(ScrAlipayEntity.class, actId);
        alipay.setMobile(mobile);
        alipay.setLastedon(new Timestamp(System.currentTimeMillis()));
        lhfDao.update(alipay);
    }

    public SrcAuthbaseEntity getAuthbaseByActid(Long actId) throws Exception {
        return lhfDao.get(SrcAuthbaseEntity.class,
                new Criteria().add("actid=? and approvestate=2", actId));
    }

    public void addLvZan(AppUserEntity appUser, Long actId) throws Exception{
        BppUserEntity bppUser = zanDao.getByPK(BppUserEntity.class, appUser.getId());
        if(bppUser != null){ //输入的旅赞商城账号存在
            ScrAlipayEntity scrAlipay = lhfDao.getByPK(ScrAlipayEntity.class, actId);
            BppCompanyEntity bppCompany = zanDao.getByPK(BppCompanyEntity.class, appUser.getCompanyid());

            //根据公司基础表中的导入数据申请Id(partnerapplyid 即对应bpp_company_apply中的openid)查询
            BppCompanyApplyEntity bppCompanyApply = zanDao.get(BppCompanyApplyEntity.class,
                    new Criteria().add("openid=?", bppCompany.getPartnerapplyid()));

            //修改app_user表中的记录
            appUser.setLhfactid(scrAlipay.getActid());
            appUser.setLfhactname(scrAlipay.getActname());
            appUser.setLhfnickname(scrAlipay.getNickname());
            appUser.setLhfrealname(scrAlipay.getRealname());
            appUser.setLhfmobile(scrAlipay.getMobile());
            appUser.setLhfemail(scrAlipay.getEmail());
            appUser.setLastedby(scrAlipay.getActid().toString());
            appUser.setLastedname(scrAlipay.getActname());
            appUser.setLastedon(new Timestamp(System.currentTimeMillis()));
            zanDao.update(appUser);

            //修改scr_alipay表中的记录
            scrAlipay.setRealname(bppUser.getRealname());
            scrAlipay.setBppagentcategory(appUser.getAgentcategory());
            scrAlipay.setBppuserid(appUser.getId());
            scrAlipay.setBppusercode(appUser.getUsecode());
            scrAlipay.setBpploginname(appUser.getLoginname());
            scrAlipay.setBppcompanyid(appUser.getCompanyid());
            scrAlipay.setBppcompanycode(appUser.getCompanycode());
            scrAlipay.setBppcompanyname(appUser.getCompanyname());
            scrAlipay.setBppbinddate(new Timestamp(System.currentTimeMillis()));
            scrAlipay.setBppaccounttype(appUser.getAccounttype());
            scrAlipay.setBppcompanyfname(bppCompany.getName());
            scrAlipay.setAccounttype(appUser.getAccounttype());
            scrAlipay.setStoreid(appUser.getStoreid());
            scrAlipay.setStorescode(appUser.getStorescode());
            scrAlipay.setStoresname(appUser.getStoresname());
            if((appUser.getAgentcategory() == 1 && appUser.getAccounttype() == 1)
                    || appUser.getAgentcategory() == 5){
                scrAlipay.setPlatactname(bppCompany.getName());
                scrAlipay.setPlatactindex(0);
            }else if(appUser.getAgentcategory() == 1 && appUser.getAccounttype() == 0){
                //获取scr_alipay表中资金金额索引
                int index = getPlatActIndexByCompanyid(appUser.getCompanyid()) + 1;
                scrAlipay.setPlatactname(bppCompany.getName() + "/" + appUser.getStoresname());  //更新需求
                scrAlipay.setPlatactindex(index);
            }
            scrAlipay.setLastedon(new Timestamp(System.currentTimeMillis()));
            lhfDao.update(scrAlipay);

            //向scr_User(用户记录绑定旅赞信息)中添加一条记录
            insertScrUser(appUser, bppCompanyApply, scrAlipay, bppCompany);
        }
    }

    public int getPlatActIndexByCompanyid(long companyId) throws Exception {
        Criteria criteria = new Criteria()
                .add("bppagentcategory=1 and accounttype=0 and bppcompanyid=?", companyId);
        Map<String, Object> map = lhfDao.getMap(ScrAlipayEntity.class, "coalesce(max(platactindex),0) as index", criteria);
        return (Integer) map.get("index");
    }

    public SrcAuthbaseEntity getAuthbaseByActId(long actId) throws Exception{
        return lhfDao.get(SrcAuthbaseEntity.class, new Criteria("actid=?", actId));
    }

    private void insertScrUser(AppUserEntity appUser,BppCompanyApplyEntity bppCompanyApply,
                           ScrAlipayEntity scrAlipay, BppCompanyEntity bppCompany) throws Exception{
        ScrUserEntity u = new ScrUserEntity();
        u.setCompanyid(appUser.getCompanyid());
        u.setCompanycode(appUser.getCompanycode());
        u.setCompanyname(appUser.getCompanyname());
        u.setUserid(appUser.getId());
        u.setUsecode(appUser.getUsecode());
        u.setLoginname(appUser.getLoginname());
        u.setUsename(appUser.getUsename());
        u.setRealname(scrAlipay.getRealname());
        u.setLpemail(scrAlipay.getEmail());
        u.setLpmobile(scrAlipay.getMobile());
        u.setLpidcard(scrAlipay.getIdcard());
        u.setCommonmobile(scrAlipay.getMobile());
        u.setLicnumber(bppCompanyApply.getBusinessnum());
        u.setIndustrynumber(bppCompanyApply.getLicensenum());
        u.setTaxnumber(bppCompanyApply.getTaxnum());
        u.setCreatedby(scrAlipay.getActid());
        u.setLastedby(scrAlipay.getActid());
        u.setBppagentcategory(appUser.getAgentcategory());
        u.setBppcompanyfname(bppCompany.getName());
        u.setProvinceid(bppCompanyApply.getProvinceid());
        u.setProvincename(bppCompanyApply.getProvincename());
        u.setCityid(bppCompanyApply.getCityid());
        u.setCityname(bppCompanyApply.getCityname());
        u.setAddress(bppCompanyApply.getAddress());
        u.setTel(bppCompanyApply.getTelnum());
        u.setFax(bppCompanyApply.getFax());
        u.setAreaid(bppCompanyApply.getCountyid());
        u.setAreaname(bppCompanyApply.getCountyname());
        u.setBppaccounttype(appUser.getAccounttype());
        u.setStoreid(appUser.getStoreid());
        u.setStorescode(appUser.getStorescode());
        u.setStoresname(appUser.getStoresname());
        lhfDao.insert(u);
    }
}
